/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package idea.ilogin;


import idea.security.Authenticator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.LifecycleManager;
import org.openide.NotifyDescriptor;
import org.openide.modules.ModuleInstall;


/**
 * Installer sets up the login frame to run before the app comes up
 * 
 * @author rejun001
 */
public class Installer extends ModuleInstall
{

    /**
     * The login frame
     */
    private LoginFrame frame = new LoginFrame();
    
    /**
     * it's a dialog window and obeys certain rules
     */
    private DialogDescriptor dd = null;
    
    /**
     * the logged in user name
     */
    private static User loggedUser;
    
    /**
     * restored: the place to bring up login frame
     */
    @Override
    public void restored()
    {
        createLoginDialog();
    }
    
    /**
     * create the login dialog
     * NOTE: buttons are created here; text fields are created in GUI builder
     */
    private void createLoginDialog() {
        JButton ok = new JButton();
        ok.setText( "OK");
        JButton chgPw = new JButton();
        chgPw.setText( "Change Password");
        JButton cancel = new JButton();
        cancel.setText( "Cancel");
        
        // cancel button
        cancel.addActionListener( new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                closeApplication();
            }
        });
        
        // OK button
        ok.addActionListener( new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                authenticate(frame.getUserName(), frame.getPassword(), frame.getDbName());
            }
        });
        
        // Change Password button
        chgPw.addActionListener( new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                // NO-OP -- this is now a back door into the App
            }
        });

        NotifyDescriptor nd = new NotifyDescriptor.Confirmation(frame, "Login");
        nd.setOptions( new Object[] { ok, chgPw, cancel } );
        DialogDisplayer.getDefault().notifyLater(nd);
        
        nd.addPropertyChangeListener( new PropertyChangeListener() { 
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (NotifyDescriptor.CLOSED_OPTION.equals( evt.getNewValue() ) ) {
                    closeApplication();
                }
            }
        });
    }
    
    /**
     * Shut down the whole thing
     */
    private void closeApplication() {
        LifecycleManager.getDefault().exit();
    }
    
    /**
     * getter for logged user
     * @return the user (User)
     */
    public static User getLoggedUser()
    {
        return loggedUser;
    }
    
    /**
     * Runs the authentication for the user
     * 
     * @param userId
     * @param password
     * @return true if authenticated
     */
    public boolean userLogging(String userId, char[] password) {
        String pw = new String(password);
        if (Authenticator.validate(userId, pw)) {
            loggedUser = User.of( userId );
            return true;         
        } else {
            return false;
        }
    }
    
    /**
     * authenticate the user/password/db name  (db name not used now)
     * @param userid
     * @param passwd
     * @param databaseName 
     */
    private void authenticate(String userid, char[] passwd, String databaseName) {
        System.out.println( "AUTHENTICATING " + userid + ", " + passwd + ", " + databaseName);
        if (userLogging(userid, passwd)) {
            // authenticated: this goes to next screen
        }else {
            System.out.println( "Invalid authentication." );
            NotifyDescriptor.Confirmation confirm = new NotifyDescriptor.Confirmation("Invalid username or password.\n\n",
                    NotifyDescriptor.OK_CANCEL_OPTION,
                    NotifyDescriptor.INFORMATION_MESSAGE);
            Object result = DialogDisplayer.getDefault().notify( confirm);
            
            if (NotifyDescriptor.YES_OPTION.equals( result ) ) {
                createLoginDialog();  // this should cover the main app screen and supersede it.
            }
            else {
                closeApplication();
            }
        }
    }
}
